// pages/puzzle/puzzle.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    x: 0,
    y: 0,
    col: 0,
    row: 0,
    puzzlePlane: {
      width: 0,
      height: 0
    },
    puzzleTexture: {
      width: 0,
      height: 0
    },
    hidden: true,
    loadImagePath: "",
    currentImages: "",
    timeTick: "",
    timeTickCount: 1,
  },

  puzzlePieces: [],
  puzzlePiecesIndex: [],
  selectTarget: {
    current: null,
    before: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let is = this

    is.setData({
      currentImages: options.currentImages,
      col: options.difficulty,
      row: options.difficulty
    })

    var query = wx.createSelectorQuery()
    query.select('#canvasPuzzle').boundingClientRect(function(res) {
      console.log(res)

      is.setData({
        puzzlePlane: {
          width: res.width,
          height: res.height
        }
      })

      is.createPreview(is.data.currentImages)
      //is.createPuzzlePlane(2, 2)
      //is.drawPuzzlePlane(2, 2)
    }).exec(function(res) {
      //console.log(res)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    let is = this
    is.stopTick()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 
   */
  start: function(e) {
    this.setData({
      hidden: false,
      x: e.touches[0].x,
      y: e.touches[0].y
    })
  },

  /**
   * 
   */
  move: function(e) {
    this.setData({
      x: e.touches[0].x,
      y: e.touches[0].y
    })
  },

  /**
   * 
   */
  end: function(e) {
    this.setData({
      hidden: true
    })

    this.checkToucheMe()
    this.checkSwapPieces()
    this.drawPuzzlePlane()
    this.checkSuccess()
  },

  /**
   *  创建预览
   */
  createPreview: function(fileName) {
    let is = this
    const ctx = wx.createCanvasContext('canvasPuzzle')

    wx.getImageInfo({
      src: fileName,
      success: function(res) {
        console.log(res)

        is.setData({
          loadImagePath: fileName, //res.path
          puzzleTexture: {
            width: res.width,
            height: res.height
          }
        })

        ctx.drawImage(is.data.loadImagePath, 0, 0, is.data.puzzlePlane.width, is.data.puzzlePlane.height)
        ctx.draw()

        is.createPuzzlePlane(is.data.col, is.data.row)
        is.randomSwapPuzzlePieces()
      }
    })

    is.startTick()
    // ctx.drawImage("/images/test.png", 0, 0, this.data.puzzlePlane.width, this.data.puzzlePlane.height);
    // ctx.draw()


    // setTimeout(function() {
    //   wx.canvasToTempFilePath({
    //     width: is.data.puzzlePlane.width,
    //     height: is.data.puzzlePlane.height,
    //     destWidth: is.data.puzzlePlane.width,
    //     destHeight: is.data.puzzlePlane.width,
    //     canvasId: 'canvasPuzzle',
    //     quality: 1,
    //     success: function(res) {
    //       is.setData({
    //         loadImagePath: res.tempFilePath,
    //       })

    //       is.createPuzzlePlane(2, 2)
    //     },
    //     fail: function(res) {
    //       console.log(res)
    //     }
    //   })
    // }, 500)
  },

  /**
   *  创建拼图 
   */
  createPuzzlePlane: function(col, row) {
    let pieceWidth = this.data.puzzlePlane.width / col
    let pieceHeight = this.data.puzzlePlane.height / row

    let pieceTextureWidth = this.data.puzzleTexture.width / col
    let pieceTextureHeight = this.data.puzzleTexture.height / row

    let index = 0
    let pieces = []
    let pieceIndex = []
    for (var x = 0; x < row; x++) {
      for (var y = 0; y < col; y++) {
        var piece = {}
        piece.id = index
        piece.x = x * pieceHeight
        piece.y = y * pieceHeight
        piece.width = pieceWidth
        piece.height = pieceHeight

        piece.uv = {}
        piece.uv.id = index
        piece.uv.x = x * pieceTextureWidth
        piece.uv.y = y * pieceTextureHeight
        piece.uv.width = pieceTextureWidth
        piece.uv.height = pieceTextureHeight

        pieces.push(piece)
        pieceIndex.push(piece.id)
        index++
      }
    }


    this.puzzlePieces = pieces
    this.puzzlePiecesIndex = pieceIndex
    this.drawPuzzlePlane()
  },

  /**
   * 绘制拼图：纹理映射(1.9.0)
   */
  drawPuzzlePlane: function() {
    let is = this
    const ctx = wx.createCanvasContext('canvasPuzzle')

    // this.data.puzzlePieces.forEach(function(piece) {
    //   ctx.drawImage(
    //     is.data.loadImagePath,
    //     piece.uv.x,
    //     piece.uv.y,
    //     piece.uv.width,
    //     piece.uv.height,
    //     piece.x,
    //     piece.y,
    //     piece.width,
    //     piece.height)
    // })

    this.puzzlePiecesIndex.forEach(function(index) {
      let piece = is.findPiece(index)
      //console.log(piece)
      ctx.drawImage(
        is.data.loadImagePath,
        piece.uv.x,
        piece.uv.y,
        piece.uv.width,
        piece.uv.height,
        piece.x,
        piece.y,
        piece.width,
        piece.height)
    })

    if (is.selectTarget.current != null) {
      ctx.setStrokeStyle('#00ff00')

      ctx.strokeRect(
        is.selectTarget.current.x,
        is.selectTarget.current.y,
        is.selectTarget.current.width,
        is.selectTarget.current.height)
    }

    ctx.draw()
  },

  /**
   * 绘制拼图：像素填充(未使用)
   */
  drawPuzzlePlaneEx: function(col, row) {
    let is = this
    const ctx = wx.createCanvasContext('canvasPuzzle')
    const pattern = ctx.createPattern(this.data.loadImagePath, 'repeat')

    //ctx.setFillStyle('red')
    //ctx.fillRect(0, 0, this.data.puzzlePlane.width, this.data.puzzlePlane.height)

    ctx.fillStyle = pattern
    this.puzzlePieces.forEach(function(piece) {
      ctx.fillRect(piece.x, piece.y, piece.width, piece.height)
    })

    ctx.draw()
  },

  /**
   * 
   */
  checkSwapPieces: function() {
    if (this.selectTarget.before != null && this.selectTarget.current != null) {
      this.swapPuzzlePieces(this.selectTarget.before.id, this.selectTarget.current.id)
      this.selectTarget.current = null
      this.selectTarget.before = null
    }
  },

  /**
   * 交换拼图块
   */
  swapPuzzlePieces: function(indexA, indexB) {
    let swapA = this.findPiece(indexA)
    let swapB = this.findPiece(indexB)
    let swapUV = swapA.uv

    swapA.uv = swapB.uv
    swapB.uv = swapUV
    //this.puzzlePiecesIndex[1] = a

    //this.adjust(this.puzzlePiecesIndex[0])
    //this.adjust(this.puzzlePiecesIndex[1])
  },

  /**
   * 随机交换
   */
  randomSwapPuzzlePieces: function() {
    console.log('random swap puzzle pieces')
    for (var index = 0; index < this.puzzlePieces.length; index++) {
      let indexA = this.randomInt(0, this.puzzlePieces.length)
      let indexB = this.randomInt(0, this.puzzlePieces.length)
      this.swapPuzzlePieces(indexA, indexB)
    }

    this.drawPuzzlePlane()
  },

  /**
   *  检测选中目标 
   */
  checkToucheMe: function() {
    let is = this
    let x = is.data.x
    let y = is.data.y
    let box = {}

    is.puzzlePieces.forEach(function(piece) {
      box.x = piece.x
      box.y = piece.y
      box.w = piece.x + piece.width
      box.h = piece.y + piece.height

      if (x >= box.x && x <= box.w &&
        y >= box.y && y <= box.h) {
        //console.log("OK:", piece)
        let before = is.selectTarget.current

        is.selectTarget.current = piece
        is.selectTarget.before = before

        return piece
      }
    })

    return null
  },

  /**
   * 
   */
  checkSuccess: function() {
    let is = this
    let success = true
    for (var index = 0; index < this.puzzlePieces.length; index++) {
      if (this.puzzlePieces[index].id != this.puzzlePieces[index].uv.id)
        success = false
    }

    if (success) {
      is.stopTick()

      wx.showModal({
        title: '提示',
        content: '挑战成功！',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.navigateTo({
              url: "/pages/success/success",
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }


    return success
  },

  /**
   * 随机数
   */
  randomInt: function(min, max) {
    return Math.floor(Math.random() * 100000) % max + min;
  },

  /**
   * 查找拼图块
   */
  findPiece: function(id) {
    for (var index = 0; index < this.puzzlePieces.length; index++) {
      if (this.puzzlePieces[index].id == id)
        return this.puzzlePieces[index]
    }

    return null
  },

  /**
   * 
   */
  adjust: function(piece) {

  },

  /**
   * 
   */
  startTick: function() {
    let is = this
    is.data.timeTick = setInterval(function() {
      let tickCount = is.data.timeTickCount + 1;
      is.setData({
        timeTickCount: tickCount
      })
    }, 2000)
  },

  /**
   * 
   */
  stopTick: function() {
    let is = this
    clearInterval(is.data.timeTick)
  },

  /**
   * 
   */
  onGiveup: function() {
    let is = this
    is.stopTick()

    wx.showModal({
      title: '提示',
      content: '您确认要放弃本次挑战吗？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.reLaunch({
            url: '/pages/index/index'
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
})